import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Select,
  InputNumber,
  Modal,
  Row,
  Space,
  DatePicker,
  message,
} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import { useEffect } from 'react';

import commonService from '@/api/services/commonService';
import { useCommon } from '@/hooks/common';
import { toFen, toYuan } from '@/utils/format-number';

export default function CouponLibPage() {
  const uri = 'coupon-lib';
  const cateName = '券码管理';
  const {
    data = {},
    ModalPros,
    searchForm,
    onSearchFormReset,
    onCreate,
    onSearch,
    refetch,
    handleChange,
  } = useCommon({ code: '', type: '', name: '' }, uri, {
    des: '',
    id: 0,
    code: '',
    expireTime: '',
    name: '',
    type: 2,
    fulMoney: 0,
    count: 1,
    money: 0,
  });

  const active = (id: string) => {
    commonService.postCustomApi(`/admin/coupon-lib/active?domainId=${id}`, {}).then(() => {
      message.success('激活成功');
      refetch();
    });
  };

  const columns: ColumnsType<any> = [
    { title: 'ID', dataIndex: 'id', align: 'center', width: 60 },
    { title: '名称', dataIndex: 'name', align: 'center', width: 60 },
    { title: '券码', dataIndex: 'code', align: 'center', width: 60 },
    { title: '过期时间', dataIndex: 'expireTime', align: 'center', width: 140 },
    {
      title: '类型',
      dataIndex: 'type',
      align: 'center',
      width: 100,
      render: (type) => <div>{type === 2 ? '模版型' : '发放型'}</div>,
    },
    { title: '描述', dataIndex: 'des', align: 'center', width: 200 },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      render: (_, record) => (
        <div className="flex w-full justify-center text-gray">
          {record.type === 2 && !record.isActive ? <div className='cursor-pointer' onClick={() => active(record.id)}>激活</div> : ''}
          {/* <IconButton onClick={() => onEdit(record)}>
            <Iconify icon="solar:pen-bold-duotone" size={18} />
          </IconButton>
          <Popconfirm
            title="确认删除该数据？"
            okText="确定"
            cancelText="取消"
            placement="left"
            onConfirm={() => doDel(record.id)}
          >
            <IconButton>
              <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
            </IconButton>
          </Popconfirm> */}
        </div>
      ),
    },
  ];

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

  return (
    <Space direction="vertical" size="large" className="w-full">
      <Card>
        <Form form={searchForm} onFinish={onSearch}>
          <Row gutter={[16, 16]}>
            <Col span={8} lg={6}>
              <Form.Item<any> label="券码" name="code" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="名称" name="name" className="!mb-0">
                <Input />
              </Form.Item>
            </Col>
            <Col span={8} lg={6}>
              <Form.Item<any> label="类型" name="type" className="!mb-0">
                <Select
                  options={[
                    { label: '全部', value: '' },
                    { label: '模版型', value: 2 },
                    { label: '发放型', value: 3 },
                  ]}
                />
              </Form.Item>
            </Col>
            <Col span={24} lg={12}>
              <div className="flex justify-end">
                <Button onClick={onSearchFormReset}>重置</Button>
                <Button type="primary" htmlType="submit" className="ml-4">
                  查询
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card
        title={cateName}
        extra={
          <div className="flex flex-row gap-[10px]">
            <Button type="primary" onClick={() => onCreate({})}>
              新增
            </Button>
          </div>
        }
      >
        <Table
          rowKey="id"
          size="small"
          pagination={{ total: data.totalCount }}
          scroll={{ x: 'max-content' }}
          columns={columns}
          dataSource={data.list}
          rowSelection={{ ...rowSelection }}
          onChange={handleChange}
        />
      </Card>

      <CommonModal {...ModalPros} />
    </Space>
  );
}

function CommonModal({ title, show, formValue, onOk, onCancel }: any) {
  const [form] = Form.useForm();
  useEffect(() => {
    form.setFieldsValue({ ...formValue, money: toYuan(formValue.money), fulMoney: toYuan(formValue.fulMoney) });
  }, [formValue, form]);
  const handleSubmit = () => {
    const params = { ...formValue, ...form.getFieldsValue() };
    params.money = toFen(params.money);
    params.fulMoney = toFen(params.fulMoney);
    params.expireTime = dayjs(params.expireTime).format('YYYY-MM-DD hh:mm:ss');
    onOk(params);
  };
  return (
    <Modal
      title={title}
      open={show}
      onOk={() => handleSubmit()}
      onCancel={onCancel}
    >
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        layout="horizontal"
      >
        <Form.Item<any> label="名称" name="name" required>
          <Input />
        </Form.Item>
        <Form.Item<any> label="优惠金额" name="money" required>
          <InputNumber suffix="元" />
        </Form.Item>
        <Form.Item<any> label="满多少使用" name="fulMoney" required>
          <InputNumber suffix="元" />
        </Form.Item>
        <Form.Item<any> label="过期时间" name="expireTime" required>
          <DatePicker />
        </Form.Item>
        <Form.Item<any> label="优惠券类型" name="type" required>
          <Select
            options={[
              { label: '模版型', value: 2 },
              { label: '发放型', value: 3 },
            ]}
          />
        </Form.Item>
        <Form.Item<any> label="每人限领" name="count" required>
          <InputNumber suffix="次" />
        </Form.Item>
        <Form.Item<any> label="优惠券说明" name="des" required>
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
}
